package cn.enilu.flash.api.controller.cust;

import cn.enilu.flash.bean.entity.cust.CarInfo;
import cn.enilu.flash.bean.vo.front.ErrorMessage;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.service.cust.CarInfoService;

import cn.enilu.flash.bean.core.BussinessLog;
import cn.enilu.flash.bean.constant.factory.PageFactory;
import cn.enilu.flash.bean.dictmap.CommonDict;
import cn.enilu.flash.bean.enumeration.BizExceptionEnum;
import cn.enilu.flash.bean.exception.GunsException;
import cn.enilu.flash.bean.vo.front.Rets;

import cn.enilu.flash.utils.BeanUtil;
import cn.enilu.flash.utils.Maps;
import cn.enilu.flash.utils.ToolUtil;
import cn.enilu.flash.utils.factory.Page;

import cn.enilu.flash.warpper.CarInfoWarpper;
import cn.enilu.flash.warpper.CustInfoWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/car")
public class CarInfoController {
	private  Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private CarInfoService carInfoService;

	@RequestMapping(value = "/list",method = RequestMethod.GET)
	public Object list(@RequestParam(required = false) String carNo,
                       @RequestParam(required = false) String communityId,
                       @RequestParam(required = false) String custId) {
	    Page<CarInfo> page = new PageFactory<CarInfo>().defaultPage();
	    page.addFilter("carNo", SearchFilter.Operator.LIKE, carNo);
	    page.addFilter("communityId", SearchFilter.Operator.EQ, communityId);
	    page.addFilter("custId", SearchFilter.Operator.EQ, custId);
        page = carInfoService.queryPage(page);
		List list = (List) new CarInfoWarpper(BeanUtil.objectsToMaps(page.getRecords())).warp();
        page.setRecords(list);
		return Rets.success(page);
	}
	@RequestMapping(method = RequestMethod.POST)
	@BussinessLog(value = "编辑车辆信息", key = "carNo",dict= CommonDict.class)
	public Object save(@ModelAttribute CarInfo carInfo){
		carInfo.setCarNo(carInfo.getCarNo().toUpperCase());
		SearchFilter sf = new SearchFilter("carNo", SearchFilter.Operator.EQ, carInfo.getCarNo());
		CarInfo tmp = carInfoService.get(sf);
		if(carInfo.getId()==null){
			if(tmp == null) {
				carInfoService.insert(carInfo);
			}else{
				return Rets.failure(ErrorMessage.DUPLICATE_CUST_CARNO);
			}
		}else {
			if(tmp == null || tmp.getId() == carInfo.getId()) {
				carInfoService.update(carInfo);
			}else{
				return Rets.failure(ErrorMessage.DUPLICATE_CUST_CARNO);
			}
		}
		return Rets.success();
	}
	@RequestMapping(method = RequestMethod.DELETE)
	@BussinessLog(value = "删除车辆信息", key = "id",dict= CommonDict.class)
	public Object remove(Long id){
		if (ToolUtil.isEmpty(id)) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		carInfoService.delete(id);
		return Rets.success();
	}
}